package com.seeyon.apps.leaveRecord.event;

import cn.hutool.core.convert.Convert;
import com.seeyon.apps.attendance.manager.AttendanceSettingManager;
import com.seeyon.cap4.batch.params.BatchRefreshParams;
import com.seeyon.cap4.batch.service.CAPBatchRefreshService;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.base.result.ServiceResult;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.content.mainbody.MainbodyManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.login.UserUtil;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static com.seeyon.apps.attendance.utils.AttendanceUtil.isWorkDay;
import static com.seeyon.apps.leaveRecord.util.CAP4FormKit.*;
import static com.seeyon.apps.leaveRecord.util.EnumUtils.getEnumItemId;
import static com.seeyon.apps.leaveRecord.util.EnumUtils.getEnumItemName;
import static com.seeyon.apps.quartz.util.CAP4FormKit.getFieldTaleId;
import static com.seeyon.apps.quartz.util.CAP4FormKit.getSubBeans;

/**
 * @Author: SPK
 * @Date: 2022/6/21 16:24
 * @Description:
 */
public class LeaveNoteEvent extends AbstractWorkflowEvent {
    protected FormApi4Cap4 formApi4Cap4;
    protected static final Log log = LogFactory.getLog(LeaveNoteEvent.class);
    private MainbodyManager ctpMainbodyManager;
    private CAPBatchRefreshService capBatchRefreshService;
    private AttendanceSettingManager attendanceSettingManager;


    public void setAttendanceSettingManager(AttendanceSettingManager attendanceSettingManager) {
        this.attendanceSettingManager = attendanceSettingManager;
    }
    @Override
    public String getId() {
        return "leaveNoteEvent";
    }

    @Override
    public String getLabel() {
        return "请假单拆分请假明细事件";
    }

    @Override
    public ApplicationCategoryEnum getAppName() {
        return ApplicationCategoryEnum.form;
    }

    @Override
    public void onProcessFinished(WorkflowEventData data) {
        try {
            User user = UserUtil.build("seeyonx", "", null);
            if (user != null) {
                UserUtil.setCurrentUser(user);
            }
            Long accountId = user.getAccountId();
            Map<String, Object> map = data.getBusinessData();
            //获取假勤档案管理表
            FormBean leaveRecord = getFormApi4Cap4().getFormByFormCode("leaveRecord");
            // 获取流程事件表单
            FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
            List<FormDataSubBean> subBeans = getSubBeans(master, "请假明细");
            AtomicReference<FormDataMasterBean> atoMasterBean = new AtomicReference();
            //获取对应档案
            getRecord(leaveRecord, master, atoMasterBean);
            FormTableBean formTableBean = leaveRecord.getTableByTableName("formson_0058");
            FormDataMasterBean masterBean = atoMasterBean.get();
            AtomicInteger num = new AtomicInteger();
            List<FormDataSubBean> formDataSubBeans = masterBean.getSubData("formson_0058");
            for (int i = 0; i < formDataSubBeans.size(); i++) {
                FormDataSubBean subBean = formDataSubBeans.get(i);
                int sort = formDataSubBeans.get(i).getSort();
                if (1 == formDataSubBeans.size() && StringUtils.isBlank(getSubFieldStrValue(subBean, "请假开始时间"))) {
                    formDataSubBeans = new ArrayList<>();
                    break;
                } else if (sort >= num.get()) {
                    num.set(sort);
                }
            }
            List<FormDataSubBean> finalFormDataSubBeans = formDataSubBeans;
            subBeans.forEach(element -> {
                String typeEnum = getSubFieldStrValue(element, "请假类型");
                String type = getEnumItemName(typeEnum);
                String days = getFieldStrValue(element, "请假天数");

                if (StringUtils.isNotBlank(type) && !"哺乳假".equals(type) && StringUtils.isNotBlank(days)) {
                    Long amId = getEnumItemId("上下午", "上午");
                    Long pmId = getEnumItemId("上下午", "下午");

                    Date startTime = (Date) getSubFieldValue(element, "请假开始时间");
                    String startNoonEnum = getSubFieldStrValue(element, "请假开始时间-上下午");

                    String startNoon = getEnumItemName(startNoonEnum);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startTime);
                    Double douDays = Double.valueOf(days);
                    if (douDays >= 0.5) {
                        douDays = douDays * 2;
                        Boolean isPlu = false;
                        for (int i = 0; i < douDays; i++) {

                            FormDataSubBean subBean = new FormDataSubBean(formTableBean, masterBean);
                            subBean.setId(UUIDLong.longUUID());
                            subBean.setFormmainId(masterBean.getId());
                            subBean.setSort(num.incrementAndGet());
                            setCellValue(subBean, "序号", num.get());
                            setCellValue(subBean, "请假天数", 0.5);
                            setCellValue(subBean, "请假类型", typeEnum);
                            if(0==i&&startNoon.equals("下午")){
                                isPlu = true;
                            }else if(isPlu){
                                if(0!=i%2){
                                    calendar.add(Calendar.DATE, 1);
                                }
                            }else if(0==i%2&&0!=i){
                                calendar.add(Calendar.DATE, 1);
                            }
                            Date date = calendar.getTime();
                            try {
                                while(!isWorkDay(date,accountId,attendanceSettingManager.getCurrentAttendanceSettingByAccountId(accountId))){
                                    calendar.add(Calendar.DATE, 1);
                                    date = calendar.getTime();
                                }
                            } catch (BusinessException e) {
                                log.info("查询是否工作日失败",e);
                            }
                             date = calendar.getTime();

                            setCellValue(subBean, "请假开始时间", date);

                            if (i == 0) {
                                setCellValue(subBean, "请假开始时间-上下午", startNoonEnum);
                            } else if ("上午".equals(startNoon)) {
                                setCellValue(subBean, "请假开始时间-上下午", 0 == i % 2 ? amId : pmId);
                            } else {
                                setCellValue(subBean, "请假开始时间-上下午", 0 == i % 2 ? pmId : amId);
                            }
                            finalFormDataSubBeans.add(subBean);

                        }
                    }
                }
            });
            masterBean.setSubData("formson_0058", finalFormDataSubBeans);
            BatchRefreshParams batchRefreshParams = new BatchRefreshParams();
            batchRefreshParams.setFormId(leaveRecord.getId());
            batchRefreshParams.setSize(1);
            ArrayList<String> ids = new ArrayList<>();
            ids.add(atoMasterBean.get().getId().toString());
            batchRefreshParams.setMasterIds(ids);
            batchRefreshParams.setExecuteRelation(true);
            leaveRecord.getBind().getUnFlowTemplateMap().keySet().forEach(element -> {
                Long authId = leaveRecord.getBind().getUnFlowTemplateMap().get(element).getId();
                batchRefreshParams.setBindAuthId(authId);
            });
            this.capBatchRefreshService = (CAPBatchRefreshService) AppContext.getBean("capBatchRefreshService");
            ServiceResult<?> serviceResult = capBatchRefreshService.batchRefresh(batchRefreshParams);
            saveContent(leaveRecord, masterBean);
        } catch (Exception e) {
            log.error("请假单拆分明细事件失败", e);
        }


    }

    /**
     * 根据提供年份、人员id获取对应的档案
     *
     * @param leaveRecord
     * @param master
     * @param masterBean
     */
    private void getRecord(FormBean leaveRecord, FormDataMasterBean master, AtomicReference<FormDataMasterBean> masterBean) {
        String userId = getFieldStrValue(master, "申请人");
        String year = getFieldStrValue(master, "年度");

        List<Map<String, Object>> count = null;
        ArrayList<Object> param = new ArrayList<>();
        param.add(year);
        param.add(userId);
        String tableName = leaveRecord.getMasterTableBean().getTableName();
        String nowYear = getFieldTaleId(leaveRecord, "当前年度");
        String name = getFieldTaleId(leaveRecord, "姓名");
        try (JDBCAgent agent = new JDBCAgent(true, false)) {
            //
            agent.execute("select id from " + tableName + " where " + nowYear + " = ? " + "and " + name + " = ?", param);
            count = agent.resultSetToList();
        } catch (Exception e) {
            log.error("查询主表出错", e);
        }

        if (count.size() > 0) {
            count.forEach(row -> {
                try {
                    masterBean.set(getFormApi4Cap4().findDataById(Convert.toLong(row.get("id")), leaveRecord.getId(), null));
                } catch (Exception e) {
                    log.error("根据id查询表单出错", e);
                }
            });
        } else {
            log.info("该人员没有对应的假勤档案");
        }
    }

    private void saveContent(FormBean formBean, FormDataMasterBean master) {
        List<CtpContentAll> contentAlls = new ArrayList<>();
        Long memberId = AppContext.getCurrentUser().getId();
        Map<String, Object> contentParams = new HashMap<>();
        contentParams.put("moduleType", ModuleType.cap4UnflowForm.getKey());
        FormBindAuthBean auth = null;
        Map<String, FormBindAuthBean> authBeans = formBean.getBind().getUnFlowTemplateMap();
        for (String key : authBeans.keySet()) {
            auth = authBeans.get(key);
            break;
        }
        contentParams.put("moduleId", Long.valueOf(auth.getId()));
        List<CtpContentAll> contentPoList = getCtpMainbodyManager().getContentList(contentParams);
// 保存ctp_content_all
        Long moduleTemplateId;
        if (null != contentPoList && contentPoList.size() > 0) {
            moduleTemplateId = contentPoList.get(0).getId();
        } else {
            log.info("没有获取到contentPoList数据");
            moduleTemplateId = auth.getId();
        }
        CtpContentAll contentAll = getContentAll(memberId, moduleTemplateId, master.getId(), formBean);
        contentAlls.add(contentAll);
        try {
            getCtpMainbodyManager().saveAll(contentAlls);
            getFormApi4Cap4().saveOrUpdateFormData(master, formBean.getId(), true);
        } catch (Exception e) {
            log.error("保存正文数据异常：", e);
        }
    }

    private CtpContentAll getContentAll(Long memberId, Long moduleTemplateId, Long masterId, FormBean bean) {
        CtpContentAll ctpContentAll = new CtpContentAll();
        ctpContentAll.setIdIfNew();
        ctpContentAll.setModuleTemplateId(moduleTemplateId);
        ctpContentAll.setModuleType(ModuleType.cap4UnflowForm.getKey());
        ctpContentAll.setModuleId(masterId);
        ctpContentAll.setContentType(20);
        ctpContentAll.setContentTemplateId(bean.getId());
        ctpContentAll.setModifyId(memberId);
        ctpContentAll.setModifyDate(new Date());
        ctpContentAll.setContentDataId(masterId);
        ctpContentAll.setCreateId(memberId);
        ctpContentAll.setCreateDate(new Date());
        ctpContentAll.setSort(0);
        return ctpContentAll;
    }

    public FormApi4Cap4 getFormApi4Cap4() {
        if (null == formApi4Cap4) {
            formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
        }
        return formApi4Cap4;
    }

    private MainbodyManager getCtpMainbodyManager() {
        if (null == ctpMainbodyManager) {
            ctpMainbodyManager = (MainbodyManager) AppContext.getBean("ctpMainbodyManager");
        }
        return ctpMainbodyManager;
    }
}
